import org.codehaus.groovy.grails.commons.ConfigurationHolder

class AuthorizeGrailsPlugin {

    def version = 0.1
    def author = "Darryl Pentz"
    def authorEmail = "djpentz@gmail.com"
    def title = "This plugin adds simple role-based authentication and authorization to a Grails application."
    def description = '''
        Authorize plugin provides a simple role-based authentication and authorization capability by
        mapping controller actions to roles. Roles can be defined in the Authorize configuration
        section in Config.groovy.
        '''
    def documentation = "http://docs.codehaus.org/display/GRAILS/Authorize+Plugin+Proposal"

    def dependsOn = [:]
    def watchedResources = "file:./grails-app/controllers/*Controller.groovy"
    def AuthService authService

    def doWithSpring = {
    }

    def doWithApplicationContext = { applicationContext ->
        log.info("Authorize plugin creating roles")
        def config = ConfigurationHolder.config
        int count = 0;
        config.authorize.roles.keySet().each {
            def aRole = AuthRole.findByName(it)
            if (!aRole) {
                log.info("Creating role ${it}")
                new AuthRole(name: it).save()
                count++
            }
        }
        if (count == 0) {
            log.info("All roles already defined by Authorize plugin")
        } else {
            log.info("Authorize plugin created ${count} roles")
        }
    }

    def doWithWebDescriptor = {xml ->
    }

    def doWithDynamicMethods = {ctx ->
    }

    def onChange = {event ->
        log.info("Reconfiguring the Authentication security settings")
        if (authService) {
            authService.tearDown();
            authService.setup();
        }
    }

    def onApplicationChange = {event ->
    }
}
